﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Web.Admin.Services.Sites;
using SaaS.Cache.Auths;
using SaaS.Model.Entity.Sites;
using SaaS.Model.Enums;
using XCore.Authorization;

namespace Web.Admin.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : AdminControllerBase
    {
        private readonly AdminAppService _adminAppService;
        private readonly AdminAuthCacheService _adminAuthCacheService;
        public AccountController(AdminAppService adminAppService, AdminAuthCacheService adminAuthCacheService)
        {
            _adminAppService = adminAppService;
            _adminAuthCacheService = adminAuthCacheService;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [Guest, HttpPost]
        public ActionResult Login(string username, string password)
        {
            return Ok(_adminAppService.Login(username, password));
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Info()
        {
            var admin = ADC.SiteAdmins.Where(c => c.SiteId == Session.SiteId && c.Id == Session.AdminId).Select(c => new
            {
                c.UserName,
                c.RoleId,
                c.Id,
            }).FirstOrDefault();
            return Ok(admin);
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Logout()
        {
            _adminAuthCacheService.RemoveTenantToken(Session.AdminId);
            return Ok(Logger.Log($"[{Session.UserName}]--退出成功", AdminLoggerSource.Login));
        }
    }
}